package com.sun.androidexerciseproject.function.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.sun.androidexerciseproject.function.logreport.util.LogUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description:
 * File: SmsReceiver.java
 * Create: 2018/12/3 0003 上午 10:18
 *
 * @author Administrator
 */
public class SmsReceiver extends BroadcastReceiver {
    private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //判断广播消息
        LogUtil.d("SmsReceiver action = " + action);
        if (action.equals(SMS_RECEIVED_ACTION)) {
            Bundle bundle = intent.getExtras();
            //如果不为空
            if (bundle != null) {
                //将pdus里面的内容转化成Object[]数组
                String format = bundle.getString("format");
                LogUtil.d("SmsReceiver onReceive format = " + format);
                // pdus ：protocol data unit  ：
                Object[] pdusData = (Object[]) bundle.get("pdus");
                int size = pdusData.length;
                LogUtil.d("SmsReceiver onReceive size = " + size);
                //解析短信
                SmsMessage[] msg = new SmsMessage[pdusData.length];
                for (int i = 0; i < msg.length; i++) {
                    byte[] pdus = (byte[]) pdusData[i];
                    msg[i] = SmsMessage.createFromPdu(pdus, format);
                }
                //获取短信内容
                StringBuffer content = new StringBuffer();
                //获取地址
                StringBuffer phoneNumber = new StringBuffer();
                //分析短信具体参数
                for (SmsMessage temp : msg) {
                    content.append(temp.getMessageBody());
                }
                LogUtil.d("sendNumber：" + msg[0].getOriginatingAddress() + "  smsContent：" + content.toString());
                Date date = new Date(msg[0].getTimestampMillis());
                SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String receiveTime = formatTime.format(date);
                LogUtil.d("receiveTime：" + receiveTime);
            }
        }
    }
}
